import Taro from '@tarojs/taro';
import { create } from 'zustand';
import { immer } from 'zustand/middleware/immer';

/**
 * @description 上传文件
 * @author Shawn
 */

const CS_APP_API = 'https://baoyouqun.cn';

type RequestFunction = (file: any) => Promise<Taro.uploadFile.SuccessCallbackResult | undefined>;

type State = {
  // 上传返回结果
  uploadRes: any;
};

type Actions = {
  // 上传文件
  uploadFiles: RequestFunction;
  uploadFiles1: RequestFunction;
};

const initialState: State = {
  uploadRes: {},
};

export const uploadStore = create<State & Actions>()(
  immer((set) => ({
    ...initialState,

    /**
     * 上传文件
     */
    uploadFiles: async (file: any) => {
      const openToken = Taro.getStorageSync('openToken');
      try {
        Taro.showLoading({
          title: '上传中',
        });
        const res = await Taro.uploadFile({
          url: `${CS_APP_API}/api/files/upload?bucket=`,
          filePath: file.url,
          name: 'file',
          header:{
            cookie: `satoken=${openToken}`,
            'content-type': 'multipart/form-data'
          }
        });
        set((state) => {
          state.uploadRes = res.data;
        });
        return res
      } catch (error) {
        console.log('上传失败', error);
      } finally {
        Taro.hideLoading();
      }
    },
    uploadFiles1: async (url: string) => {
      const openToken = Taro.getStorageSync('openToken');
      try {
        Taro.showLoading({
          title: '上传中',
        });
        const res = await Taro.uploadFile({
          url: `${CS_APP_API}/api/files/upload?bucket=`,
          filePath: url,
          name: 'file',
          header:{
            cookie: `satoken=${openToken}`,
            'content-type': 'multipart/form-data'
          }
        });
        set((state) => {
          state.uploadRes = res.data;
        });
        return res
      } catch (error) {
        console.log('上传失败', error);
      } finally {
        Taro.hideLoading();
      }
    },
  })),
);
